<template>
  <el-dialog title="修改密码" v-model="showDialog" @close="handleClose" width="600px" class="padding_10">
    <el-form :model="formData" label-width="80px" :rules="rules" ref="form">
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" auto-complete="off" placeholder="请输入新密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirm_password">
        <el-input placeholder="请输入确认密码" v-model="formData.confirm_password" show-password></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="handleClose" size="medium">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="onSubmit()" size="medium">提 交</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage} from "element-plus";
import {resetPassword} from '../api/user'
import {reactive, toRefs, onMounted, computed, watch, ref} from 'vue'

export default {
  name: "RestPassword",
  props: {
    dialogShow: {
      type: Boolean,
      default: false,
      required: true,
    },
    user_id: {
      type: Number,
      required: true,
    }
  },
  setup(props, context) {
    const state = reactive({
      showDialog: false,
      formData: {
        password: null,
        confirm_password: null,
      }
    })

    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== state.formData.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const rules = {
      password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 6, max: 24, message: "长度在 6 到 24 个字符", trigger: "blur"},
      ],
      confirm_password: [
        {required: true, message: '请输入确认密码', trigger: 'blur'},
        {validator: validatePass, trigger: 'blur'}
      ],
    }

    watch(() => props.dialogShow, (val) => state.showDialog = val)

    const form = ref(null)

    const handleClose = () => {
      form.value.resetFields()

      context.emit('update:dialogShow', false)
    }

    const onSubmit = () => {
      form.value.validate((valid) => {
        if (!valid) {
          console.log('error submit!!')
          return false
        }

        resetPassword(props.user_id, state.formData.password).then((result) => {
          state.showDialog = false
          context.emit('update:dialogShow', false)

          ElMessage.success('执行成功')
        })
      })
    }

    return {
      ...toRefs(state),
      handleClose,
      onSubmit,
      form,
      rules,
    }
  }
}
</script>

<style scoped>

</style>